<script setup lang="tsx">
import { ref, computed } from 'vue'
import { ElMessage, ElLoading } from 'element-plus'
import { adminBusinessMemberCardApi, adminBusinessMemberCardPayApi } from '@/api/MerchantAccount'

const emits = defineEmits(['close'])

const formData = ref({
  id: '',
  cardName: '',
  payType: '2' // 支付方式(1-微信，2-网银对公)
})

// 待支付金额，含手续费12
const payAmt = computed(() => {
  if (formData.value.id) {
    const obj = dataList.value.find((it) => it.id === formData.value.id)
    return (obj && obj.cardCost + 12) || 0
  }
  return 0
})

const onItemSelect = (item) => {
  formData.value.id = item.id
  formData.value.cardName = item.cardName
}

const toPay = async () => {
  if (!formData.value.id) {
    ElMessage.error('请先选择次卡类型!')
    return
  }
  const loadingInstance = ElLoading.service({ fullscreen: true })
  try {
    const res = await adminBusinessMemberCardPayApi({
      id: formData.value.id
    })
    loadingInstance.close()
    if (res.code === 200) {
      emits('close', { payAmt: payAmt.value, cardName: formData.value.cardName })
      window.open(res.data.fromUrl, '_blank')
    } else {
      ElMessage.error(res.message)
    }
  } catch (error) {
    loadingInstance.close()
  }
}

const dataList = ref<any>([])
const getList = () => {
  adminBusinessMemberCardApi({
    pageNum: 1,
    pageSize: 100
  }).then((res) => {
    if (res.code === 200) {
      dataList.value = res.data.list
    } else {
      ElMessage.error(res.message)
    }
  })
}

getList()
</script>

<template>
  <div>
    <div class="mb-10px">请选择</div>
    <div class="h-400px overflow-auto mb-16px">
      <div
        v-for="(item, i) in dataList"
        :key="i"
        class="flex justify-between items-center pl-20px pr-40px py-10px border border-solid rounded-lg mb-16px"
        :class="formData.id === item.id ? 'border-red-600' : 'border-dark-200'"
        @click="onItemSelect(item)"
      >
        <div>
          <div class="text-18px font-bold text-dark-200">{{ item.cardName }}</div>
          <div class="text-14px text-dark-200">活动发布次数：{{ item.activeCount }}</div>
        </div>
        <div class="text-20px text-red-600">
          <span class="text-14px">¥</span>{{ item.cardCost }}
        </div>
      </div>
    </div>
    <div class="mb-10px">支付方式</div>
    <div>
      <el-radio-group v-model="formData.payType">
        <el-radio label="2">网银打款</el-radio>
      </el-radio-group>
      <div class="text-xs">（每笔收取12元手续费）</div>
    </div>
    <div class="flex flex-col justify-end items-end">
      <el-button
        style="height: 70px; padding: 0 50px; line-height: 70px"
        type="danger"
        @click="toPay"
      >
        <div class="flex flex-col text-xs py-4">
          <div>
            <span>¥</span><span class="text-[25px]">{{ payAmt }}</span
            >（含手续费）
          </div>
          <div class="text-lg">立即支付</div>
        </div>
      </el-button>
    </div>
  </div>
</template>
